import { IAiPicItem, IMessageItem, IResultMessgeItem } from "@/components/Message/type";
import { MSG_TYPE } from "./config";

// 消息后缀
export const getMsgSuffix = (params:Partial<IMessageItem>) => { 
    return ` --style ${params.style} --format ${params.format} --definition ${'' + params.definition}`
}

// 格式化后端返回的messageList数据
export const formatMessage = (resultMsgList: IResultMessgeItem[], startIndex: number) => {
    const jobList: { index: number; jobId: string; isBig: boolean }[] = []
    // 历史消息任务状态对应的消息显示类型
    const statusTypeMap: {[key:string]:string} = {
        'END': MSG_TYPE.FINISH,
        'FAIL': MSG_TYPE.ERROR,
        'CLOSE': MSG_TYPE.CANCEL,
        'WAITING': MSG_TYPE.WATTING,
        'RUNNING': MSG_TYPE.GENERATING,
    }
    const formatList = resultMsgList.reverse().map((msg, index) => {
        const isBig = msg.is_synthesis === '3'
        const isOver = msg.status === 'END'
        const isClose = msg.status === 'CLOSE'
        const isFail = msg.status === 'FAIL'
        // 需要继续执行任务的保存起来
        if (!isOver && !isFail && !isClose) {
            jobList.push({
                index: startIndex + index,
                jobId: msg.jobid,
                //用来判断是走放大的任务轮询还是普通的任务轮询
                isBig
            })
        }
        const num = msg.num || 4
        // 如果是放大图的任务消息或者是没有预览图的任务消息，不展示预览图
        let list:IAiPicItem[] = []
        if (isBig || !msg.preview) {
            list = msg.list
        } else { 
            list = [{ preview: msg.preview,isSynthesis:true, id: Date.now() }, ...msg.list]
        }
        return {
            id: msg.id,
            type:statusTypeMap[msg.status],
            job: isOver ? '' : msg.jobid,
            content: (`${msg.prompt}${getMsgSuffix(msg)}`),
            created: msg.created,
            isBig,
            pid: msg.pid,
            step: msg.list.length * 100 / num,
            definition: msg.definition,
            num,
            style: msg.style,
            format: msg.format,
            is_synthesis: msg.is_synthesis,
            picList: list.map(item => {
                return {
                    ...item,
                    id: item.id ? +item.id : 0
                }
            })
        }
    })

    return {
        formatList,
        jobList
    }
}

export default () => { }